Top Tags

macOS CLI Handbook

Quick reference for essential macOS terminal commands — file management, system info, networking, disk utilities, process control, package management, and more.

Terminal Basics

Opening Terminal

bash
1# Spotlight → type "Terminal" → Enter
2# Or: Applications → Utilities → Terminal
3
4# Popular terminal alternatives:
5# iTerm2, Warp, Alacritty, Kitty, Hyper

Essential Keyboard Shortcuts

bash
1Ctrl + A # Move cursor to beginning of line
2Ctrl + E # Move cursor to end of line
3Ctrl + U # Delete entire line (before cursor)
4Ctrl + K # Delete to end of line
5Ctrl + W # Delete word before cursor
6Ctrl + R # Reverse search command history
7Ctrl + C # Cancel current command
8Ctrl + D # Exit shell / EOF
9Ctrl + Z # Suspend current process (resume with fg)
10Ctrl + L # Clear screen (same as clear)
11Tab # Autocomplete file/directory names
12Tab Tab # Show all possible completions

Command History

bash
1history # Show command history
2history 20 # Show last 20 commands
3!! # Re-run the last command
4!n # Run command number n from history
5!string # Run last command starting with "string"
6!$ # Last argument of previous command
7Ctrl + R # Reverse search through history
8fc # Open last command in editor

Shell Configuration

Zsh Config Files (Default Shell)

bash
1~/.zshrc # Main zsh config (loaded for interactive shells)
2~/.zprofile # Login shell config (loaded once at login)
3~/.zshenv # Always loaded (all zsh invocations)
4~/.zsh_history # Command history file
5~/.zlogout # Executed on logout

Bash Config Files (Legacy)

bash
1~/.bash_profile # Login shell config
2~/.bashrc # Interactive non-login shell config
3~/.bash_history # Command history
4~/.bash_logout # Executed on logout

Useful Aliases

bash
1# Add to ~/.zshrc
2alias ll='ls -la'
3alias la='ls -A'
4alias l='ls -CF'
5alias ..='cd ..'
6alias ...='cd ../..'
7alias cls='clear'
8alias grep='grep --color=auto'
9alias rm='rm -i' # Confirm before deleting
10alias cp='cp -i' # Confirm before overwriting
11alias mv='mv -i' # Confirm before overwriting
12alias ports='lsof -i -P -n | grep LISTEN'
13alias myip='curl -s ifconfig.me'
14alias flushdns='sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder'

Environment Variables

bash
1echo $PATH # Show current PATH
2echo $HOME # Home directory
3echo $SHELL # Current shell
4echo $USER # Current username
5printenv # List all environment variables
6export VAR_NAME="value" # Set environment variable (current session)
7# Add to ~/.zshrc for persistence:
8export PATH="$HOME/bin:$PATH" # Prepend to PATH

Change Default Shell

bash
1chsh -s /bin/zsh # Switch to zsh
2chsh -s /bin/bash # Switch to bash
3cat /etc/shells # List available shells
4echo $SHELL # Show current default shell

Important macOS Paths

System Directories

bash
1/ # Root filesystem
2/System/ # macOS system files (read-only, SIP protected)
3/Library/ # System-wide libraries and support files
4~/Library/ # User-specific libraries and app data
5/Applications/ # Installed applications
6/Users/ # User home directories
7/usr/local/ # Homebrew (Intel Mac) and local software
8/opt/homebrew/ # Homebrew (Apple Silicon)
9/private/var/ # Variable data (logs, tmp, etc.)
10/private/etc/ # System configuration files
11/tmp/ # Temporary files (symlink to /private/tmp)

Configuration & Preferences

bash
1~/Library/Preferences/ # App preference files (.plist)
2~/Library/Application Support/ # App data and configs
3~/Library/Caches/ # App cache files
4~/Library/Logs/ # User app logs
5~/Library/LaunchAgents/ # User-level launch agents (auto-start)
6/Library/LaunchAgents/ # System-wide launch agents
7/Library/LaunchDaemons/ # System-wide launch daemons (root services)
8~/Library/Containers/ # Sandboxed app data
9~/Library/Group Containers/ # Shared data between apps

Log Files

bash
1/var/log/system.log # Main system log (legacy)
2/var/log/install.log # Installation logs
3/var/log/wifi.log # Wi-Fi logs
4/var/log/apache2/ # Apache web server logs
5~/Library/Logs/ # User application logs
6~/Library/Logs/DiagnosticReports/ # Crash reports
7# Modern macOS uses unified logging:
8log show --last 1h # Show last hour of logs
9log show --predicate 'process == "kernel"' --last 30m # Kernel logs
10log stream # Live log stream

File & Directory Management

bash
1pwd # Print current directory
2cd /path/to/dir # Change directory
3cd ~ # Go to home directory
4cd - # Go to previous directory
5cd .. # Go up one level
6cd ../.. # Go up two levels
7pushd /path/to/dir # Push directory onto stack and cd
8popd # Pop directory from stack and cd back
9dirs -v # Show directory stack

Listing Files

bash
1ls # List files
2ls -l # Long format (permissions, size, date)
3ls -la # Long format including hidden files
4ls -lh # Long format with human-readable sizes
5ls -lS # Sort by file size (largest first)
6ls -lt # Sort by modification time (newest first)
7ls -lR # List recursively
8ls -1 # One file per line
9ls -d */ # List only directories

Creating Files & Directories

bash
1touch file.txt # Create empty file or update timestamp
2mkdir dirname # Create directory
3mkdir -p path/to/nested/dir # Create nested directories
4mktemp # Create a temporary file
5mktemp -d # Create a temporary directory

Copying, Moving & Renaming

bash
1cp source.txt dest.txt # Copy file
2cp -r source_dir/ dest_dir/ # Copy directory recursively
3cp -i source.txt dest.txt # Interactive (confirm overwrite)
4mv oldname.txt newname.txt # Rename file
5mv file.txt /path/to/dest/ # Move file
6ditto source/ dest/ # macOS-native copy (preserves metadata)
7ditto -V source/ dest/ # Verbose ditto copy
8rsync -av source/ dest/ # Sync files (fast incremental copy)
9rsync -av --delete src/ dest/ # Sync and delete extra files in dest

Deleting Files & Directories

bash
1rm file.txt # Delete file
2rm -f file.txt # Force delete (no confirmation)
3rm -r dirname/ # Delete directory recursively
4rm -rf dirname/ # Force delete directory
5rmdir dirname # Delete empty directory only
6trash file.txt # Move to Trash (if trash CLI installed)
7# macOS native: move to Trash via Finder or use `mv file ~/.Trash/`

File Permissions & Ownership

bash
1chmod 755 script.sh # Set permissions (rwxr-xr-x)
2chmod +x script.sh # Add execute permission
3chmod -R 644 directory/ # Set permissions recursively
4chown user:group file.txt # Change file owner and group
5chown -R user:group dir/ # Change owner recursively
6ls -l # View permissions
7stat -f '%A %N' file.txt # Show octal permissions (macOS)
bash
1ln -s /path/to/original link # Create symbolic link
2ln /path/to/original hardlink # Create hard link
3readlink link_name # Show where symlink points
4ls -la # Symlinks shown with -> target

Viewing & Editing Files

Viewing File Contents

bash
1cat file.txt # Display entire file
2less file.txt # View file (scrollable, press q to quit)
3more file.txt # View file (page by page)
4head file.txt # Show first 10 lines
5head -n 20 file.txt # Show first 20 lines
6tail file.txt # Show last 10 lines
7tail -n 20 file.txt # Show last 20 lines
8tail -f logfile.log # Follow file in real-time (great for logs)
9wc file.txt # Count lines, words, bytes
10wc -l file.txt # Count lines only

Text Editors (Terminal)

bash
1nano file.txt # Simple editor (Ctrl+O save, Ctrl+X exit)
2vi file.txt # Vi editor (i=insert, Esc :wq=save+quit)
3vim file.txt # Vim (improved vi)
4open -e file.txt # Open in TextEdit
5code file.txt # Open in VS Code (if installed)

File Information

bash
1file myfile # Detect file type
2stat file.txt # Detailed file info (size, dates, etc.)
3mdls file.txt # Spotlight metadata attributes
4xattr file.txt # List extended attributes
5xattr -d com.apple.quarantine file # Remove quarantine flag
6GetFileInfo file.txt # HFS+ attributes

Searching & Finding

Find Files

bash
1find / -name "filename" # Find file by name (whole system)
2find . -name "*.txt" # Find .txt files in current dir
3find . -type f -name "*.log" # Find files only (not directories)
4find . -type d -name "src" # Find directories only
5find . -size +100M # Find files larger than 100MB
6find . -mtime -7 # Files modified in last 7 days
7find . -mtime +30 # Files modified more than 30 days ago
8find . -empty # Find empty files and directories
9find . -name "*.tmp" -delete # Find and delete files
10find . -name "*.sh" -exec chmod +x {} \; # Find and execute command

Spotlight Search (macOS-Specific)

bash
1mdfind "search query" # Search using Spotlight index
2mdfind -name "filename" # Search by filename
3mdfind -onlyin ~/Documents "report" # Search in specific directory
4mdfind "kMDItemKind == 'PDF'" # Search by file kind
5mdls file.txt # Show Spotlight metadata for a file
6mdutil -s / # Check Spotlight indexing status
7mdutil -E / # Erase and rebuild Spotlight index

Search Inside Files

bash
1grep "pattern" file.txt # Search for pattern in file
2grep -r "pattern" directory/ # Search recursively in directory
3grep -i "pattern" file.txt # Case-insensitive search
4grep -n "pattern" file.txt # Show line numbers
5grep -l "pattern" *.txt # List files containing pattern
6grep -c "pattern" file.txt # Count matching lines
7grep -v "pattern" file.txt # Show lines NOT matching
8grep -E "regex" file.txt # Extended regex (egrep)

Locate Files

bash
1locate filename # Fast file search using database
2sudo /usr/libexec/locate.updatedb # Update locate database
3which command # Show path of a command
4whereis command # Show binary/man/source paths
5type command # Show how command would be interpreted

Text Processing

Common Tools

bash
1sort file.txt # Sort lines alphabetically
2sort -n file.txt # Sort numerically
3sort -r file.txt # Reverse sort
4sort -u file.txt # Sort and remove duplicates
5uniq file.txt # Remove adjacent duplicate lines
6uniq -c file.txt # Count occurrences of each line
7cut -d',' -f1,3 data.csv # Extract columns 1 and 3 (comma delimited)
8cut -c1-10 file.txt # Extract first 10 characters per line
9paste file1.txt file2.txt # Merge lines of files side-by-side
10tr 'a-z' 'A-Z' < file.txt # Convert to uppercase
11tr -d '\r' < file.txt # Remove carriage returns (Windows → Unix)

sed & awk

bash
1sed 's/old/new/' file.txt # Replace first occurrence per line
2sed 's/old/new/g' file.txt # Replace all occurrences
3sed -i '' 's/old/new/g' file # In-place edit (macOS sed)
4sed -n '5,10p' file.txt # Print lines 5 to 10
5awk '{print $1}' file.txt # Print first column
6awk -F',' '{print $2}' data.csv # Print 2nd column (comma delimiter)
7awk '{sum+=$1} END {print sum}' file.txt # Sum first column

Redirection & Pipes

bash
1command > file.txt # Redirect stdout to file (overwrite)
2command >> file.txt # Append stdout to file
3command 2> error.log # Redirect stderr to file
4command &> output.log # Redirect stdout and stderr
5command 2>&1 # Redirect stderr to stdout
6command1 | command2 # Pipe output of cmd1 to cmd2
7command | tee file.txt # Output to screen AND file
8command | tee -a file.txt # Append to file AND show on screen

System Information

macOS Version & Hardware

bash
1sw_vers # macOS version details
2sw_vers -productVersion # Just the version number
3uname -a # Kernel version and architecture
4uname -m # CPU architecture (arm64 / x86_64)
5system_profiler SPHardwareDataType # Detailed hardware info
6system_profiler SPSoftwareDataType # Software overview
7sysctl -n machdep.cpu.brand_string # CPU model name
8sysctl -n hw.memsize # Total memory (bytes)
9sysctl hw.ncpu # Number of CPUs
10arch # Print architecture (arm64 / i386)

Disk & Storage

bash
1df -h # Disk space usage (human-readable)
2df -H # Disk space (powers of 1000)
3du -sh * # Size of each item in current dir
4du -sh directory/ # Total size of a directory
5du -sh * | sort -rh | head -10 # Top 10 largest items
6diskutil list # List all disks and partitions
7diskutil info disk0 # Info about a specific disk
8diskutil apfs list # List APFS volumes
9diskutil eraseDisk APFS "Name" disk2 # Erase and format disk

Memory & CPU

bash
1top # Real-time process monitor (q to quit)
2htop # Improved top (install via brew)
3top -l 1 -s 0 | head -n 12 # Snapshot of system stats
4vm_stat # Virtual memory statistics
5sysctl hw.memsize # Total physical memory
6memory_pressure # Memory pressure status
7powermetrics --samplers cpu_power -n 1 # CPU power usage (sudo)

Uptime & Users

bash
1uptime # System uptime and load average
2w # Who is logged in and what they're doing
3who # Currently logged in users
4whoami # Current username
5id # Current user ID, group ID
6last # List last logins

Process Management

Viewing Processes

bash
1ps aux # All running processes (detailed)
2ps aux | grep process_name # Find a specific process
3pgrep -l process_name # Find process by name (with PID)
4top # Real-time process viewer
5top -o cpu # Sort by CPU usage
6top -o mem # Sort by memory usage
7lsof # List all open files
8lsof -i :8080 # What is using port 8080
9lsof -c process_name # Files opened by a process

Killing Processes

bash
1kill PID # Send TERM signal to process
2kill -9 PID # Force kill (SIGKILL)
3kill -HUP PID # Send hangup signal (reload config)
4killall process_name # Kill all processes by name
5killall -9 process_name # Force kill all by name
6pkill process_name # Kill by partial name match
7pkill -f "pattern" # Kill by full command line match

Background & Foreground

bash
1command & # Run command in background
2jobs # List background jobs
3fg # Bring last job to foreground
4fg %1 # Bring job 1 to foreground
5bg %1 # Resume job 1 in background
6nohup command & # Run command immune to hangup (persists after logout)
7disown %1 # Detach job from shell

Launch Agents & Daemons (Startup Services)

bash
1launchctl list # List all loaded services
2launchctl list | grep my-service # Find a specific service
3launchctl load ~/Library/LaunchAgents/com.my.plist # Load/start a service
4launchctl unload ~/Library/LaunchAgents/com.my.plist # Unload/stop a service
5launchctl start com.my.service # Start a service by label
6launchctl stop com.my.service # Stop a service by label
7sudo launchctl kickstart -k system/com.apple.mDNSResponder # Restart system service

Networking

Network Information

bash
1ifconfig # Show network interfaces
2ifconfig en0 # Show Wi-Fi interface details
3ipconfig getifaddr en0 # Get local IP address (Wi-Fi)
4curl -s ifconfig.me # Get public IP address
5curl -s ipinfo.io # Detailed public IP info (JSON)
6networksetup -listallhardwareports # List all network ports
7networksetup -getinfo Wi-Fi # Wi-Fi connection info
8scutil --dns # Show DNS configuration
9cat /etc/resolv.conf # DNS resolver config
10hostname # Show hostname
11scutil --get HostName # Get hostname
12sudo scutil --set HostName name # Set hostname

Testing Connectivity

bash
1ping google.com # Ping a host (Ctrl+C to stop)
2ping -c 5 google.com # Ping 5 times then stop
3traceroute google.com # Trace route to host
4mtr google.com # Combined ping + traceroute (install via brew)
5curl -I https://example.com # HTTP headers only
6curl -o file.zip https://url # Download file
7curl -L https://url # Follow redirects
8wget https://url # Download file (install via brew)
9networkQuality # Test network quality (macOS 12+)
10networkQuality -v # Verbose network quality test

DNS

bash
1nslookup domain.com # DNS lookup
2dig domain.com # Detailed DNS lookup
3dig domain.com +short # Short DNS answer
4host domain.com # Simple DNS lookup
5dscacheutil -flushcache # Flush DNS cache
6sudo killall -HUP mDNSResponder # Restart DNS resolver

Ports & Connections

bash
1netstat -an # Show all connections
2netstat -an | grep LISTEN # Show listening ports
3lsof -i -P -n # List all network connections
4lsof -i :80 # What is using port 80
5lsof -i :8080 # What is using port 8080
6sudo lsof -iTCP -sTCP:LISTEN -n -P # All listening TCP ports

Firewall

bash
1sudo pfctl -s info # Packet filter info
2sudo pfctl -e # Enable firewall
3sudo pfctl -d # Disable firewall
4sudo pfctl -f /etc/pf.conf # Reload firewall rules
5/usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate # App firewall status
6sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setglobalstate on # Enable app firewall

SSH

bash
1ssh user@hostname # Connect to remote host
2ssh -p 2222 user@hostname # Connect on custom port
3ssh -i ~/.ssh/key.pem user@host # Connect with specific key
4ssh-keygen -t ed25519 # Generate SSH key (recommended type)
5ssh-keygen -t rsa -b 4096 # Generate RSA SSH key
6ssh-copy-id user@hostname # Copy public key to remote host
7scp file.txt user@host:/path/ # Secure copy file to remote
8scp user@host:/path/file.txt . # Secure copy file from remote
9scp -r dir/ user@host:/path/ # Copy directory recursively

Package Management (Homebrew)

Install Homebrew

bash
1# Install Homebrew
2/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
3
4# Verify installation
5brew --version

Common Homebrew Commands

bash
1brew search package # Search for a package
2brew install package # Install a package
3brew uninstall package # Uninstall a package
4brew list # List installed packages
5brew info package # Show package info
6brew update # Update Homebrew itself
7brew upgrade # Upgrade all packages
8brew upgrade package # Upgrade specific package
9brew outdated # List outdated packages
10brew cleanup # Remove old versions
11brew cleanup -s # Remove all cached downloads
12brew doctor # Diagnose issues
13brew deps package # Show dependencies
14brew uses package --installed # Show what depends on a package

Homebrew Casks (GUI Applications)

bash
1brew install --cask app-name # Install GUI application
2brew uninstall --cask app-name # Uninstall GUI application
3brew list --cask # List installed casks
4brew outdated --cask # List outdated casks
5brew upgrade --cask # Upgrade all casks
6
7# Common casks:
8brew install --cask google-chrome
9brew install --cask visual-studio-code
10brew install --cask iterm2
11brew install --cask docker
12brew install --cask rectangle # Window management

Homebrew Services

bash
1brew services list # List all services
2brew services start service # Start a service
3brew services stop service # Stop a service
4brew services restart service # Restart a service
5brew services run service # Run without auto-start on login

Disk & Volume Management

Disk Utility CLI

bash
1diskutil list # List all disks and partitions
2diskutil info /dev/disk0 # Info about a specific disk
3diskutil mountDisk /dev/disk2 # Mount a disk
4diskutil unmountDisk /dev/disk2 # Unmount a disk
5diskutil eject /dev/disk2 # Eject external disk
6diskutil mount /dev/disk2s1 # Mount a specific partition
7diskutil unmount /dev/disk2s1 # Unmount a specific partition
8diskutil verifyVolume / # Verify boot volume
9diskutil repairVolume / # Repair boot volume
10diskutil apfs list # List APFS containers and volumes

Mounts & Filesystems

bash
1mount # Show all mounted filesystems
2mount | grep -i "disk" # Show disk mounts
3mount_smbfs //user@server/share /mnt # Mount SMB share
4umount /mnt/point # Unmount a filesystem
5hdiutil attach disk-image.dmg # Mount a DMG image
6hdiutil detach /dev/disk2 # Unmount a DMG image
7hdiutil create -size 1g -fs APFS -volname "MyDisk" my.dmg # Create DMG

Compression & Archives

Common Commands

bash
1# ZIP
2zip archive.zip file1 file2 # Create zip archive
3zip -r archive.zip directory/ # Zip a directory recursively
4unzip archive.zip # Extract zip
5unzip -l archive.zip # List contents without extracting
6
7# TAR
8tar -czf archive.tar.gz dir/ # Create gzipped tarball
9tar -cjf archive.tar.bz2 dir/ # Create bzip2 tarball
10tar -xzf archive.tar.gz # Extract gzipped tarball
11tar -xjf archive.tar.bz2 # Extract bzip2 tarball
12tar -tf archive.tar.gz # List contents of tarball
13tar -xzf archive.tar.gz -C /dest/ # Extract to specific directory
14
15# GZIP
16gzip file.txt # Compress (replaces original)
17gzip -k file.txt # Compress (keep original)
18gunzip file.txt.gz # Decompress

User & Permissions Management

User Information

bash
1whoami # Current username
2id # User ID, group ID, groups
3id -un # Username only
4groups # List groups for current user
5dscl . list /Users # List all local users
6dscl . list /Groups # List all local groups
7dscl . read /Users/username # User details
8finger username # User info

Sudo & Privileges

bash
1sudo command # Run command as root
2sudo -s # Open root shell
3sudo -u user command # Run command as another user
4sudo !! # Re-run last command with sudo
5visudo # Edit sudoers file safely

macOS-Specific Commands

System Preferences & Defaults

bash
1# Show hidden files in Finder
2defaults write com.apple.finder AppleShowAllFiles -bool true
3killall Finder
4
5# Hide hidden files again
6defaults write com.apple.finder AppleShowAllFiles -bool false
7killall Finder
8
9# Show full path in Finder title bar
10defaults write com.apple.finder _FNDShowPathbar -bool true
11
12# Screenshot location
13defaults write com.apple.screencapture location ~/Desktop/Screenshots
14killall SystemUIServer
15
16# Screenshot format (png, jpg, pdf, tiff)
17defaults write com.apple.screencapture type png
18
19# Disable screenshot shadow
20defaults write com.apple.screencapture disable-shadow -bool true
21
22# Show all file extensions
23defaults write NSGlobalDomain AppleShowAllExtensions -bool true
24
25# Disable auto-correct
26defaults write NSGlobalDomain NSAutomaticSpellingCorrectionEnabled -bool false
27
28# Key repeat speed (lower = faster)
29defaults write NSGlobalDomain KeyRepeat -int 2
30defaults write NSGlobalDomain InitialKeyRepeat -int 15
31
32# Read current default
33defaults read com.apple.finder AppleShowAllFiles

Open Command

bash
1open . # Open current directory in Finder
2open file.txt # Open file with default app
3open -a "Safari" https://url # Open URL in Safari
4open -a "Visual Studio Code" . # Open current dir in VS Code
5open -R file.txt # Reveal file in Finder
6open /Applications/ # Open Applications folder
7open -e file.txt # Open in TextEdit

Screenshots

bash
1screencapture screen.png # Full screen capture
2screencapture -i region.png # Interactive region capture
3screencapture -w window.png # Capture specific window
4screencapture -c # Capture to clipboard
5screencapture -T 5 delayed.png # Capture after 5-second delay
6screencapture -x silent.png # Capture without sound

Clipboard

bash
1echo "text" | pbcopy # Copy text to clipboard
2pbpaste # Paste from clipboard
3pbpaste > file.txt # Paste clipboard to file
4cat file.txt | pbcopy # Copy file contents to clipboard
5pbpaste | sort | pbcopy # Sort clipboard contents

Say (Text to Speech)

bash
1say "Hello World" # Read text aloud
2say -f file.txt # Read file aloud
3say -v ? # List available voices
4say -v Samantha "Hello" # Use specific voice
5say -o output.aiff "Hello" # Save speech to audio file

System Control

bash
1sudo shutdown -h now # Shutdown immediately
2sudo shutdown -h +30 # Shutdown in 30 minutes
3sudo shutdown -r now # Restart immediately
4sudo reboot # Restart
5pmset sleepnow # Put Mac to sleep
6caffeinate # Prevent sleep (Ctrl+C to stop)
7caffeinate -t 3600 # Prevent sleep for 1 hour
8caffeinate -s # Prevent sleep while on AC power
9osascript -e 'tell app "System Events" to log out' # Log out

Software Updates

bash
1softwareupdate -l # List available updates
2softwareupdate -ia # Install all available updates
3softwareupdate -ir # Install recommended updates
4softwareupdate --history # Show update history

Spotlight

bash
1mdutil -s / # Check Spotlight indexing status
2mdutil -i on / # Enable Spotlight indexing
3mdutil -i off / # Disable Spotlight indexing
4mdutil -E / # Erase and rebuild index
5mdfind "search term" # Search via Spotlight
6mdfind -name "filename" # Search files by name

Security & Privacy

bash
1# System Integrity Protection (SIP)
2csrutil status # Check SIP status
3# To enable/disable SIP, boot into Recovery Mode (Cmd+R)
4
5# Gatekeeper
6spctl --status # Check Gatekeeper status
7sudo spctl --master-disable # Disable Gatekeeper
8sudo spctl --master-enable # Enable Gatekeeper
9
10# Keychain
11security find-generic-password -a "account" -s "service" # Find password
12security list-keychains # List keychains
13
14# FileVault (disk encryption)
15fdesetup status # Check FileVault status
16sudo fdesetup enable # Enable FileVault

Git Quick Reference

Basic Commands

bash
1git init # Initialize repository
2git clone url # Clone repository
3git status # Check status
4git add . # Stage all changes
5git add file.txt # Stage specific file
6git commit -m "message" # Commit with message
7git push # Push to remote
8git pull # Pull from remote

Branching

bash
1git branch # List branches
2git branch new-branch # Create branch
3git checkout branch-name # Switch branch
4git checkout -b new-branch # Create and switch
5git merge branch-name # Merge branch
6git branch -d branch-name # Delete branch

Useful Git Commands

bash
1git log --oneline # Compact log
2git log --graph --oneline # Visual branch log
3git diff # Show unstaged changes
4git stash # Stash changes
5git stash pop # Apply stashed changes
6git remote -v # Show remotes
7git reset --hard HEAD # Discard all changes

Cron & Scheduling

Crontab

bash
1crontab -l # List cron jobs
2crontab -e # Edit cron jobs
3crontab -r # Remove all cron jobs

Cron Syntax

bash
1# ┌───────── minute (0 - 59)
2# │ ┌─────── hour (0 - 23)
3# │ │ ┌───── day of month (1 - 31)
4# │ │ │ ┌─── month (1 - 12)
5# │ │ │ │ ┌─ day of week (0 - 7, 0 and 7 = Sunday)
6# │ │ │ │ │
7# * * * * * command
8
9# Examples:
100 * * * * command # Every hour
11*/15 * * * * command # Every 15 minutes
120 9 * * 1-5 command # Weekdays at 9 AM
130 0 * * * command # Daily at midnight
140 0 1 * * command # First of every month
15@reboot command # At startup

Useful One-Liners

File Operations

bash
1# Find and delete .DS_Store files
2find . -name ".DS_Store" -delete
3
4# Find large files (>100MB)
5find / -type f -size +100M 2>/dev/null
6
7# Count files in directory
8find . -type f | wc -l
9
10# Compare two directories
11diff -rq dir1/ dir2/
12
13# Generate a file checksum
14shasum -a 256 file.txt
15md5 file.txt

System Maintenance

bash
1# Free up disk space
2brew cleanup && rm -rf ~/Library/Caches/*
3
4# Show top 20 largest files
5find / -type f -exec du -h {} + 2>/dev/null | sort -rh | head -20
6
7# List all listening ports with process names
8sudo lsof -iTCP -sTCP:LISTEN -n -P
9
10# Kill process on a specific port
11lsof -ti :3000 | xargs kill -9
12
13# Watch a command run every 2 seconds
14watch -n 2 'kubectl get pods' # (install via brew)

Text & Data

bash
1# Count lines in all .py files
2find . -name "*.py" -exec cat {} + | wc -l
3
4# Remove duplicate lines from a file
5sort file.txt | uniq > cleaned.txt
6
7# Generate a random password
8openssl rand -base64 24
9
10# Generate UUID
11uuidgen
12
13# Encode/decode base64
14echo "text" | base64 # Encode
15echo "dGV4dAo=" | base64 -d # Decode
16
17# JSON pretty print
18cat file.json | python3 -m json.tool
19echo '{"key":"val"}' | jq . # Using jq (install via brew)

Common Shortnames & Aliases

AbbreviationFull Form
~Home directory (/Users/username)
.Current directory
..Parent directory
-Previous directory (for cd)
/Root directory
*Wildcard (matches any characters)
?Wildcard (matches single character)
>Redirect output (overwrite)
>>Redirect output (append)
``
&Run command in background
&&Run next command if previous succeeds
`
;Run next command regardless
!!Repeat last command
!$Last argument of previous command